<template>
  <div class="home-area flex-box">
    <div class="item left flex-box-left" v-if="shownLeft">
      <HomeLeft :designer="designer" ref="toolbarRef"/>
    </div>
    <div class="item middle flex-box-right" :class="{'hide-left':!shownLeft}">
      <HomeMiddle
          ref="formRef"
          :designer="designer"
          :global-dsv="globalDsv"
          :form-config="designer.formConfig"
          @handleDeleteWidget="handleDeleteWidget"
          @handleBackTemplateInfo="handleBackTemplateInfo"
      />
    </div>
    <div class="item right flex-box-right">
      <HomeRight
          :designer="designer"
          :global-dsv="globalDsv"
          :form-config="designer.formConfig"
          :selected-widget="designer.selectedWidget"
          @edit-event-handler="handleTest"
      />
    </div>
  </div>
</template>

<script>
import axios from "axios"
import i18n, {changeLocale} from "@/utils/vue-i18n/i18n"
import HomeLeft from './modules/homeLeft';
import HomeRight from './modules/homeRight';
import HomeMiddle from './modules/homeMiddle';
import SvgIcon from '@/components/public/svg-icon'
import {MOCK_CASE_URL, VARIANT_FORM_VERSION} from "@/utils/designer/config"
import {createDesigner} from "@/components/public/form-designer/designer"
import {containers, bizFields, customFields, sceneFields} from "@c/public/form-designer/widgetsConfig"
import {
  getAllContainerWidgets,
  getAllFieldWidgets,
  getQueryParam,
  traverseAllWidgets
} from "@/utils/designer/util"
import {deepClone} from "@/utils/common"

export default {
  name: 'TemplateDetails',

  componentName: "VFormDesigner",

  mixins: [i18n],

  components: {
    HomeLeft,
    HomeMiddle,
    HomeRight,
    SvgIcon,
  },

  props: {
    /* 后端字段列表API */
    fieldListApi: {
      type: Object,
      default: null,
    },

    /* 禁止显示的组件名称数组 */
    bannedWidgets: {
      type: Array,
      default: () => []
    },

    designerConfig: {
      type: Object,
      default: () => {
        return {
          languageMenu: true,         //是否显示语言切换菜单
          externalLink: true,         //是否显示GitHub、文档等外部链接
          formTemplates: true,        //是否显示表单模板
          eventCollapse: true,        //是否显示组件事件属性折叠面板
          widgetNameReadonly: false,  //禁止修改组件名称
          clearDesignerButton: true,  //是否显示清空设计器按钮
          previewFormButton: true,    //是否显示预览表单按钮
          importJsonButton: true,     //是否显示导入JSON按钮
          exportJsonButton: true,     //是否显示导出JSON器按钮
          exportCodeButton: true,     //是否显示导出代码按钮
          generateSFCButton: true,    //是否显示生成SFC按钮
          toolbarMaxWidth: 420,       //设计器工具按钮栏最大宽度（单位像素）
          toolbarMinWidth: 300,       //设计器工具按钮栏最小宽度（单位像素）
          presetCssCode: '',          //设计器预设CSS样式代码
          resetFormJson: false,       //是否在设计器初始化时将表单内容重置为空
        }
      }
    },

    /* 全局数据源变量 */
    globalDsv: {
      type: Object,
      default: () => ({})
    },

  },

  data() {
    return {
      caseName: '',
      fieldList: [],
      curLangName: '',
      vsCodeFlag: false,
      designer: createDesigner(this),
      vFormVersion: VARIANT_FORM_VERSION,
    }
  },

  computed: {
    // 右侧选择是否显示
    shownLeft() {
      let {type} = (this.$route.params);
      switch (type) {
        case 'create':
        case 'detail':
          return true;
        case 'edit':
          return false
      }
    },

  },

  provide() {
    return {
      serverFieldList: () => this.fieldList,
      getDesignerConfig: () => this.designerConfig,
      getBannedWidgets: () => this.bannedWidgets,
    }
  },

  created() {
    this.vsCodeFlag = getQueryParam('vscode') === 1
    this.caseName = getQueryParam('case');
  },

  mounted() {
    this.initLocale();
    this.loadCase()
    this.loadFieldListFromServer();
    // 获取号别简称的字段
    this.$store.dispatch('templateDetails/setRegisterObjNameOptions', 'sys_screen_obj_key');
  },

  methods: {
    // 回传后台的数据
    handleBackTemplateInfo() {},

    handleTest(eventName, eventParams) {
      console.log('test-1', eventName)
      console.log('test-2', eventParams)
    },

    loadCase() {
      if (!this.caseName) {
        return
      }
      axios.get(MOCK_CASE_URL + this.caseName + '.txt').then(res => {
        if (!!res.data.code) {
          this.$message.error(this.i18nt('designer.hint.sampleLoadedFail'))
          return
        }
        this.setFormJson(res.data)
        this.$message.success(this.i18nt('designer.hint.sampleLoadedSuccess'))
      }).catch(error => {
        this.$message.error(`${this.i18nt('designer.hint.sampleLoadedFail')}:${error}`)
      })
    },

    initLocale() {
      let curLocale = localStorage.getItem('v_form_locale')
      if (!!this.vsCodeFlag) {
        curLocale = curLocale || 'en-US'
      } else {
        curLocale = curLocale || 'zh-CN'
      }
      this.curLangName = this.i18nt('application.' + curLocale)
      this.changeLanguage(curLocale)
    },

    loadFieldListFromServer() {
      if (!this.fieldListApi) {
        return
      }
      let headers = this.fieldListApi.headers || {}
      axios.get(this.fieldListApi.URL, {'headers': headers}).then(res => {
        let labelKey = this.fieldListApi['labelKey'] || 'label'
        let nameKey = this.fieldListApi['nameKey'] || 'name'
        this.fieldList.splice(0, this.fieldList.length)  //清空已有
        res.data.forEach(fieldItem => {
          this.fieldList.push({
            name: fieldItem[nameKey],
            label: fieldItem[labelKey],
          })
        })
      }).catch(error => {
        this.$message.error(error)
      })
    },

    changeLanguage(langName) {
      changeLocale(langName)
    },

    setFormJson(formJson) {
      let modifiedFlag = false
      if (!!formJson) {
        if (typeof formJson === 'string') {
          modifiedFlag = this.designer.loadFormJson(JSON.parse(formJson))
        } else if (formJson.constructor === Object) {
          modifiedFlag = this.designer.loadFormJson(formJson)
        }
        if (modifiedFlag) {
          this.designer.emitHistoryChange()
        }
      }
    },

    getFormJson() {
      return {
        widgetList: deepClone(this.designer.widgetList),
        formConfig: deepClone(this.designer.formConfig)
      }
    },

    clearDesigner() {
      this.$refs.toolbarRef.clearFormWidget()
    },

    handleDeleteWidget(val) {
      console.log(this.designer.widgetList)
    },

    /**
     * 刷新表单设计器
     */
    refreshDesigner() {
      //this.designer.loadFormJson( this.getFormJson() )  //只有第一次调用生效？？
      let fJson = this.getFormJson()
      this.designer.clearDesigner(true)  //不触发历史记录变更
      this.designer.loadFormJson(fJson)
    },

    /**
     * 预览表单
     */
    previewForm() {
      this.$refs.toolbarRef.previewForm()
    },

    /**
     * 导入表单JSON
     */
    importJson() {
      this.$refs.toolbarRef.importJson()
    },

    /**
     * 导出表单JSON
     */
    exportJson() {
      this.$refs.toolbarRef.exportJson()
    },

    /**
     * 导出Vue/HTML代码
     */
    exportCode() {
      this.$refs.toolbarRef.exportCode()
    },

    /**
     * 生成SFC代码
     */
    generateSFC() {
      this.$refs.toolbarRef.generateSFC()
    },

    /**
     * 获取所有字段组件
     * @returns {*[]}
     */
    getFieldWidgets(widgetList = null) {
      return !!widgetList ? getAllFieldWidgets(widgetList) : getAllFieldWidgets(this.designer.widgetList)
    },

    /**
     * 获取所有容器组件
     * @returns {*[]}
     */
    getContainerWidgets(widgetList = null) {
      return !!widgetList ? getAllContainerWidgets(widgetList) : getAllContainerWidgets(this.designer.widgetList)
    },

    /**
     * 升级表单json，以补充最新的组件属性
     * @param formJson
     */
    upgradeFormJson(formJson) {
      if (!formJson.widgetList || !formJson.formConfig) {
        this.$message.error('Invalid form json!')
        return
      }

      traverseAllWidgets(formJson.widgetList, (w) => {
        this.designer.upgradeWidgetConfig(w)
      })
      this.designer.upgradeFormConfig(formJson.formConfig)
      return formJson
    },

    getWidgetRef(widgetName, showError = false) {
      return this.$refs['formRef'].getWidgetRef(widgetName, showError)
    },

    getSelectedWidgetRef() {
      return this.$refs['formRef'].getSelectedWidgetRef()
    },
  }

}
</script>


<style lang="scss" scoped>
@import "./assets/style";
</style>